package com.duoduo.demo.webuploader;

import java.io.File;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

@Controller
public class AppController {
	private Logger logger = LoggerFactory.getLogger(getClass());

	/**
	 * 首页
	 * 
	 * @return
	 */
	@RequestMapping("/")
	public String page(Model model) {
		model.addAttribute("name", "cgs");
		return "index";
	}

	@RequestMapping("uploader")
	public void upload(HttpServletRequest request, HttpServletResponse response) {
		MultipartHttpServletRequest Murequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> files = Murequest.getFileMap();// 得到文件map对象
		String upaloadUrl = request.getSession().getServletContext().getRealPath("/") + "upload/";// 得到当前工程路径拼接上文件名
		logger.info("附件上传路径：{}", upaloadUrl);

		File dir = new File(upaloadUrl);
		if (!dir.exists()) {// 目录不存在则创建
			dir.mkdirs();
		}

		for (MultipartFile file : files.values()) {
			String fileName = file.getOriginalFilename();
			File tagetFile = new File(upaloadUrl + fileName);// 创建文件对象
			if (!tagetFile.exists()) {// 文件名不存在 则新建文件，并将文件复制到新建文件中
				try {
					tagetFile.createNewFile();
					file.transferTo(tagetFile);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}
}
